//
//  FirstViewController.swift
//  LaiLang
//
//  Created by David on 2017/2/3.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit

class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    var customNavBar: LLNavBar!
    var locationSelBtn: UIButton!
    var searchBarButton: UIButton!
    
    var tableView: UITableView!
    var refreshControl: LLRefreshControl!
    
    var slider: LLSlider!
    var sliderImageView: [UIImageView] = []
    
    var cardBG: UIView!
    var functionSlider: LLCollectionSlider!
    var functionCollections: [LLCollection]!
    
    var activityCollection: LLCollection!
    
    var recommandList: NSArray?
    var popularList: NSArray?

//    var listHeadViewFixPos : UIView!
//    var listHeadView: UIView!
//    var headTabView: UIView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        navigationController?.setNavigationBarHidden(true, animated: false)
        
        tableView = UITableView(frame: CGRect(x: 0, y: -20, width: view.bounds.width, height: view.bounds.height + 20), style: .grouped)
//        tableView.tableFooterView = UIView(frame: CGRect.zero)
//        tableView.backgroundColor = UIColor.groupTableViewBackground
        view.addSubview(tableView)
        
        refreshControl = LLRefreshControl(frame: CGRect(x: 0, y: -64, width: view.bounds.width, height: 64))
        tableView.addSubview(refreshControl)
        
        // 渲染导航栏
        customNavBar = LLNavBar(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 64))
        customNavBar.barTintColor = themeColor
        view.addSubview(customNavBar)
        customNavBar.barAlpht = 0
        
        locationSelBtn = UIButton(frame: CGRect(x: 16, y: 20, width: 72, height: 44))
        locationSelBtn.addTarget(self, action: #selector(FirstViewController.gotoLocation), for: .touchUpInside)
        
        customNavBar.addSubview(locationSelBtn)
        let savedLocation = UserDefaults.standard.string(forKey: LLSavedLocationKey)
        if savedLocation != nil {
            
        }else{
            setLocationBtnText(text: "选择定位")
        }
        locationSelBtn.contentHorizontalAlignment = .left
        
        
        searchBarButton = UIButton(frame: CGRect(x: 16 + 72 + 16, y: 28, width: view.bounds.width - 32 - 72 - 16, height: 28))
        setSearchBarText(text: "搜索")
        searchBarButton.titleLabel?.textAlignment = .left
        searchBarButton.backgroundColor = UIColor(white: 1, alpha: 0.5)
        searchBarButton.layer.cornerRadius = 14
        customNavBar.addSubview(searchBarButton)
        searchBarButton.addTarget(self, action: #selector(FirstViewController.gotoSearch), for: .touchUpInside)
        
        // 渲染首页部件
        
        // 渲染轮播图
        initSliderImage()
        
        // 渲染功能格子
        initFunctionsCollection()
        
        // 渲染活动展示
        initActivityCollectionImage()
        
//        headTabView = UIView(frame: CGRect(x: -0.5, y: -0.5, width: view.bounds.width+1, height: 32+1))
//        headTabView.backgroundColor = UIColor.white
//        headTabView.layer.borderColor = UIColor.lightGray.cgColor
//        headTabView.layer.borderWidth = 0.5
//        
//        let btn1 = UIButton(frame: CGRect(x: 0, y: 4, width: view.bounds.width/3, height: 20))
//        btn1.tag = 0
//        btn1.setTitle("热门动态", for: .normal)
//        btn1.setTitleColor(UIColor.black, for: .normal)
//        btn1.titleLabel?.font = UIFont.systemFont(ofSize: 14)
//        headTabView.addSubview(btn1)
//        btn1.addTarget(self, action: #selector(FirstViewController.gotoTopic(sender:)), for: .touchUpInside)
//        
//        let bottomLine = UIView(frame: CGRect(x: 32, y: 29, width: view.bounds.width/3 - 64, height: 4))
//        bottomLine.backgroundColor = themeColor
//        headTabView.addSubview(bottomLine)
//        
//        let btn2 = UIButton(frame: CGRect(x: view.bounds.width/3, y: 4, width: view.bounds.width/3, height: 20))
//        btn2.tag = 1
//        btn2.setTitle("热门话题", for: .normal)
//        btn2.setTitleColor(UIColor.black, for: .normal)
//        btn2.titleLabel?.font = UIFont.systemFont(ofSize: 14)
//        headTabView.addSubview(btn2)
//        btn2.addTarget(self, action: #selector(FirstViewController.gotoTopic(sender:)), for: .touchUpInside)
//        
//        let btn3 = UIButton(frame: CGRect(x: view.bounds.width/3*2, y: 4, width: view.bounds.width/3, height: 20))
//        btn3.tag = 2
//        btn3.setTitle("推荐话题", for: .normal)
//        btn3.setTitleColor(UIColor.black, for: .normal)
//        btn3.titleLabel?.font = UIFont.systemFont(ofSize: 14)
//        headTabView.addSubview(btn3)
//        btn3.addTarget(self, action: #selector(FirstViewController.gotoTopic(sender:)), for: .touchUpInside)
//        listHeadView =
//        listHeadView.addSubview(headTabView)
        
        
//        listHeadViewFixPos = NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: headTabView)) as! UIView
//        listHeadViewFixPos.frame = CGRect(x: -0.5, y: 64-0.5, width: view.bounds.width+1, height: 32.5)
//        listHeadViewFixPos.layer.borderColor = UIColor.lightGray.cgColor
//        listHeadViewFixPos.layer.borderWidth = 0.5
////        listHeadViewFixPos.backgroundColor = UIColor.white
////        listHeadViewFixPos.addSubview(headTabView)
//        view.addSubview(listHeadViewFixPos)
        
//        LLRefreshPage()
        
        tableView.delegate = self
        tableView.dataSource = self
        
        navigationController?.interactivePopGestureRecognizer?.delegate = nil
    }
    
    func LLRefreshPage(){
        refreshControl.beginRefresh()
        var insert = tableView.contentInset
        insert.top += 64
        tableView.contentInset = insert
        
        
        LLGetSliderImage()
        LLGetActivityImage()
        LLGetRecommand()
        LLGetPopular()
        
//        popularList = [
//            ["user":"yonghu", "avatar":"", "time":"2017-02-12 12:12:12", "follow":"0", "content":"这电脑好便宜，配置又高", "like_num":384, "comment":322, "pic":["","",""]],
//            ["user":"yonghu", "avatar":"", "time":"2017-02-12 12:12:12", "follow":"0", "content":"震惊!1800X领先i7 6900K幅度为9% 价格还不到其一半! 美国旧金山当地时间2月21日，AMD 总裁兼首席执行官Lisa SU女士正式公布了 AMD Ryzen 7处理器型号、性能表现、价格以及发售时间。", "like_num":384, "comment":294, "pic":["","","",""]],
//            ["user":"yonghu", "avatar":"", "time":"2017-02-12 12:12:12", "follow":"0", "content":"g4560确实强啊 本人的是amd760k的 准备换处理器 看了一下 g4560确实强 有什么建议", "like_num":384, "comment":294, "pic":["","","","",""]],
//            ["user":"yonghu", "avatar":"", "time":"2017-02-12 12:12:12", "follow":"0", "content":"老板给了1W块叫给他配台电脑", "like_num":384, "comment":294, "pic":[]],
//            ["user":"yonghu", "avatar":"", "time":"2017-02-12 12:12:12", "follow":"0", "content":"我想知道我这个配置亏不亏可以不可以玩gt5求大神看看", "like_num":384, "comment":294, "pic":["","","","","","",""]],
//            ["user":"yonghu", "avatar":"", "time":"2017-02-12 12:12:12", "follow":"0", "content":"如何用1500打造性价比最高机", "like_num":"", "comment":294, "pic":["","","","","","","","",""]]
//        ]
        
        
        if #available(iOS 10.0, *) {
            Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { (timer) in
                self.refreshControl.endRefresh()
                
//                self.tableView.setContentOffset(self.tableView.contentOffset, animated: true)
                var insert = self.tableView.contentInset
                insert.top -= 64
                UIView.animate(withDuration: 0.3, animations: { 
                    self.tableView.contentInset = insert
                })
                self.tableView.reloadData()
//                self.tableView.setContentOffset(CGPoint(x: 0, y: -20), animated: true)
            }
        } else {
            
        }
    }
    
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        hidesBottomBarWhenPushed = false
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1//2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0:
            return 1
//        case 1:
//            return 1
//        case 1:
//            if recommandList != nil {
//                if recommandList!.count != 0{
//                    return recommandList!.count
//                }
//            }
//            return 1
        case 1:
            if popularList != nil {
                if popularList!.count != 0{
                    return popularList!.count
                }
            }
            return 1
        default:
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.section {
        case 0:
            switch indexPath.row {
            case 0:
                return slider.bounds.height + functionSlider.bounds.height + 24 + activityCollection.bounds.height
            default:
                break
            }
//        case 1:
//            return activityCollection.bounds.height
        case 1:
//            if indexPath.row == 0{
//                return 32
//            }
            var height:CGFloat = 64.0 + 40.0
            let thisData = popularList?.object(at: indexPath.row) as? NSDictionary
            let content = thisData?.object(forKey: "content") as? String
            if content != nil{
                
                height += (content! as NSString).boundingRect(with: CGSize(width: view.bounds.width - 88, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 14)], context: nil).height + 16
            }
            
            let pics = thisData?.object(forKey: "pic") as? NSArray
            if pics != nil{
                if pics!.count != 0{
                    height += CGFloat((pics!.count-1) / 3 + 1)*homeTopicImgSize
                }
                
            }
            
            return height
        case 2:
            if indexPath.row == 0{
                return 32
            }
            return 80
        default:
            break
        }
        return 44
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0{
            return 0.001
        }
        
        if section == 1{
            return 32
        }
        
        return 16
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//        if section == 1{
//            let headView = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 32))
//            headView.addSubview(headTabView)
//            return headView
//        }
        return nil
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "item")
        cell.selectionStyle = .none
        switch indexPath.section {
        case 0:
            
            switch indexPath.row {
            case 0:
                cell.backgroundColor = UIColor.groupTableViewBackground
                cell.addSubview(slider)
                cell.addSubview(cardBG)
                cell.addSubview(activityCollection)
                break
            default:
                break
            }
            break
//        case 1:
//            if indexPath.row == 0 {
//                cell.addSubview(activityCollection)
//            }
//            break
        case 1:
//            if indexPath.row == 0 {
//                cell.selectionStyle = .none
//                let views = getTitleBtnHeader(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 32), title: "推荐频道", btnText: "更多")
//                cell.addSubview(views.show)
//                views.action.addTarget(self, action: #selector(FirstViewController.gotoMoreRecommand), for: .touchUpInside)
//                
//            }else{
//                //var empty = true
//            }
            
            var empty = true
            if popularList != nil {
                if popularList!.count != 0{
                    empty = false
                    
                    
                    
                    let avatarImg = UIButton(frame: CGRect(x: 16, y: 8, width: 48, height: 48))
                    avatarImg.backgroundColor = UIColor.lightGray
                    cell.addSubview(avatarImg)
                    
                    let nameLabel = UILabel(frame: CGRect(x: 72, y: 8, width: view.bounds.width - 88 - 72, height: 20))
                    cell.addSubview(nameLabel)
                    
                    let timeLabel = UILabel(frame: CGRect(x: 72, y: 36, width: view.bounds.width - 88 - 72, height: 20))
                    timeLabel.font = UIFont.systemFont(ofSize: 14)
                    timeLabel.textColor = UIColor.lightGray
                    cell.addSubview(timeLabel)
                    
                    let followBtn = UIButton(frame: CGRect(x: view.bounds.width - 72, y: 8, width: 64, height: 28))
                    followBtn.setTitleColor(themeColor, for: .normal)
                    followBtn.layer.borderColor = themeColor.cgColor
                    followBtn.layer.borderWidth = 1
                    followBtn.layer.cornerRadius = 4
                    followBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
                    cell.addSubview(followBtn)
                    
                    let thisData = popularList?.object(at: indexPath.row) as? NSDictionary
                    let uname = thisData?.object(forKey: "user") as? String
                    let time = thisData?.object(forKey: "time") as? String
                    let avatar = thisData?.object(forKey: "avatar") as? String
                    let follow = thisData?.object(forKey: "follow") as? String
                    
                    
                    nameLabel.text = uname
                    timeLabel.text = time
                    followBtn.setTitle(follow == "1" ? "取消关注" : "关注", for: .normal)
                    let imgUrl = URL(string: avatar ?? "")
                    if imgUrl != nil{
                        
                        URLSession.shared.dataTask(with: imgUrl!, completionHandler: { (data:Data?, resp:URLResponse?, err:Error?) in
                            // TODO: 获取头像
                        })
                    }
                    
                    let content = thisData?.object(forKey: "content") as? String
                    
                    var contentHeight:CGFloat = 0.0
                    if content != nil{
                        contentHeight = (content! as NSString).boundingRect(with: CGSize(width: view.bounds.width - 88, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 14)], context: nil).height
                        let contentLabel = UILabel(frame: CGRect(x: 72, y: 64 + 8, width: view.bounds.width - 88, height: contentHeight))
                        contentLabel.font = UIFont.systemFont(ofSize: 14)
                        contentLabel.numberOfLines = 0
                        cell.addSubview(contentLabel)
                        contentLabel.text = content
                    }
                    
                    let pics = thisData?.object(forKey: "pic") as? NSArray
                    
                    var imagesHeight:CGFloat = 0.0
                    
                    if pics != nil{
                        let picsCount = pics!.count
                        if picsCount != 0{
                            imagesHeight = homeTopicImgSize * CGFloat((picsCount-1)/3 + 1)
                            let imgsView = UIView(frame: CGRect(x: 72, y: 80 + contentHeight, width: view.bounds.width - 88 - 72, height: imagesHeight))
                            
                            if picsCount == 4{
                                for i in 0..<picsCount {
                                    let iv = UIButton(frame: CGRect(x: CGFloat(i%2)*homeTopicImgSize , y: CGFloat(i/2)*homeTopicImgSize, width: homeTopicImgSize - 4, height: homeTopicImgSize - 4))
                                    iv.backgroundColor = UIColor.lightGray
                                    imgsView.addSubview(iv)
                                }
                                
                            }else{
                                
                                for i in 0..<picsCount {
                                    let iv = UIButton(frame: CGRect(x: CGFloat(i%3)*homeTopicImgSize , y: CGFloat(i/3)*homeTopicImgSize, width: homeTopicImgSize - 4, height: homeTopicImgSize - 4))
                                    iv.backgroundColor = UIColor.lightGray
                                    imgsView.addSubview(iv)
                                }
                                
                            }
                            cell.addSubview(imgsView)
                        }
                    }
                    
                    let likeBtn = UIButton(frame: CGRect(x: 72, y: 80 + contentHeight + imagesHeight + 8, width: 72, height: 20))
                    cell.addSubview(likeBtn)
                    let likeBtnTitle = "\u{e6a4} \(thisData?.object(forKey: "like_num") as? Int ?? 0)"
                    var attrStr = NSMutableAttributedString(string: likeBtnTitle)
                    attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGray, range: NSMakeRange(0, likeBtnTitle.characters.count))
                    attrStr.addAttribute(NSFontAttributeName, value: UIFont(name: "iconfont", size: 16)!, range: NSMakeRange(0, 1))
                    attrStr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 14), range: NSMakeRange(1, likeBtnTitle.characters.count - 1))
                    likeBtn.setAttributedTitle(attrStr, for: .normal)
                    
                    let commentBtn = UIButton(frame: CGRect(x: 72 + 80, y: 80 + contentHeight + imagesHeight + 8, width: 72, height: 20))
                    let commentBtnTitle = "\u{e621} \(thisData?.object(forKey: "comment") as? Int ?? 0)"
                    cell.addSubview(commentBtn)
                    
                    attrStr = NSMutableAttributedString(string: commentBtnTitle)
                    attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGray, range: NSMakeRange(0, commentBtnTitle.characters.count))
                    attrStr.addAttribute(NSFontAttributeName, value: UIFont(name: "iconfont", size: 16)!, range: NSMakeRange(0, 1))
                    attrStr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 14), range: NSMakeRange(1, commentBtnTitle.characters.count - 1))
                    commentBtn.setAttributedTitle(attrStr, for: .normal)
                    
                    let favBtn = UIButton(frame: CGRect(x: 72 + 80 + 80, y: 80 + contentHeight + imagesHeight + 8, width: 72, height: 20))
                    favBtn.setTitle("收藏", for: .normal)
                    favBtn.setTitleColor(UIColor.lightGray, for: .normal)
                    favBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
                    cell.addSubview(favBtn)
                    
                }
            }
            if empty {
                cell.addSubview(showNothingPlaceholder(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 80)))
            }
            
            break
        case 2:
            if indexPath.row == 0 {
                cell.selectionStyle = .none
                let views = getTitleBtnHeader(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 32), title: "热门频道", btnText: "更多")
                cell.addSubview(views.show)
                views.action.addTarget(self, action: #selector(FirstViewController.gotoMorePopular), for: .touchUpInside)
                
            }else{
                var empty = true
                if popularList != nil {
                    if popularList!.count != 0{
                        empty = false
//                        let index = indexPath.row - 1
                    }
                }
                if empty {
                    cell.addSubview(showNothingPlaceholder(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 80)))
                }
            }
            
            break
        default:
            break
        }
        return cell
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        if scrollView.contentOffset.y < -96 {
            if refreshControl.state == .Normal {
                refreshControl.readyToRefresh()
            }
        }else{
            if refreshControl.state == .Ready{
                refreshControl.endRefresh()
            }
        }
        
        if scrollView.contentOffset.y <= 0{
            customNavBar.barAlpht = 0
            searchBarButton.backgroundColor = UIColor(white: 1, alpha: 0.5)
        }else if scrollView.contentOffset.y <= 64 {
            customNavBar.barAlpht = scrollView.contentOffset.y / 64.0
            if searchBarButton.backgroundColor == UIColor.white {
                UIView.animate(withDuration: 0.3, animations: {
                    self.searchBarButton.backgroundColor = UIColor(white: 1, alpha: 0.5)
                })
            }
            
        }else if scrollView.contentOffset.y > 64{
            customNavBar.barAlpht = 1
            if searchBarButton.backgroundColor != UIColor.white {
                UIView.animate(withDuration: 0.3, animations: {
                    self.searchBarButton.backgroundColor = UIColor.white
                })
            }
            
            
        }
//        print("\(scrollView.contentOffset.y + 20)|\(slider.bounds.height + functionSlider.bounds.height + 24 + activityCollection.bounds.height + 16 - 64)")
//        if scrollView.contentOffset.y + 20 > slider.bounds.height + functionSlider.bounds.height + 24 + activityCollection.bounds.height + 16 - 64{
//            listHeadViewFixPos.alpha = 1
//        }else{
//            listHeadViewFixPos.alpha = 0
//        }
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if refreshControl.state == .Ready {
            LLRefreshPage()
            
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func initSliderImage(){
        slider = LLSlider(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 200))
        slider.backgroundColor = UIColor.gray
        
        var i = 1
        
        while FileManager.default.fileExists(atPath: "\(CACHES_PATH)/slider/\(i).jpg") {
            let image = UIImage(contentsOfFile: "\(CACHES_PATH)/slider/\(i).jpg")
            let imageView = UIImageView(image: image)
            sliderImageView.append(imageView)
            i += 1
        }
        
        if sliderImageView.count == 0 {
            let image1 = UIImageView(image: UIImage(contentsOfFile: Bundle.main.path(forResource: "swiperone", ofType: "png")!))
            let image2 = UIImageView(image: UIImage(contentsOfFile: Bundle.main.path(forResource: "swipertwo", ofType: "png")!))
            
            sliderImageView.append(image1)
            sliderImageView.append(image2)
            
        }
        
        slider.imageViews = sliderImageView
        
        LLGetSliderImage()
    }
    
    func LLGetSliderImage(){
        
        
        // TODO: 获取网络图
    }
    
    func setLocationBtnText(text: String){
        let showText = "\(text)\u{e61f}"
        let attrStr = NSMutableAttributedString(string: showText)
        
        attrStr.addAttribute(NSFontAttributeName, value: UIFont(name: "iconfont", size: 14)!
            , range: NSMakeRange(text.characters.count, 1))
        attrStr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 14), range: NSMakeRange(0, text.characters.count))
        attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.white, range: NSMakeRange(0, showText.characters.count))
        locationSelBtn.setAttributedTitle(attrStr, for: .normal)
    }
    
    func setSearchBarText(text: String){
        let showText = "\u{e639}\(text)"
        let attrStr = NSMutableAttributedString(string: showText)
        
        attrStr.addAttribute(NSFontAttributeName, value: UIFont(name: "iconfont", size: 14)!
            , range: NSMakeRange(0, 1))
        attrStr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 14), range: NSMakeRange(1, text.characters.count))
        attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGray, range: NSMakeRange(0, showText.characters.count))
        searchBarButton.setAttributedTitle(attrStr, for: .normal)
    }
    
    func initFunctionsCollection(){
        cardBG = UIView(frame: CGRect(x: 8, y: slider.bounds.height - 8, width: view.bounds.width - 16, height: 144 + 16))
        cardBG.backgroundColor = UIColor.white
        cardBG.layer.cornerRadius = 8
        
        functionSlider = LLCollectionSlider(frame: CGRect(x: 0, y: 0, width: view.bounds.width - 16, height: 144))
        cardBG.addSubview(functionSlider)
        
        functionCollections = []
        functionCollections.append(LLCollection(frame: CGRect(x: 0, y: 0, width: functionSlider.frame.width, height: functionSlider.frame.height), row: 2, column: 4))
        functionCollections.append(LLCollection(frame: CGRect(x: 0, y: 0, width: functionSlider.frame.width, height: functionSlider.frame.height), row: 2, column: 4))
        functionSlider.views = functionCollections
        
        let first = functionCollections[0]
        first.setItemIcon(at: 0, iconUnicode: "\u{e6f9}")
        first.setItemIcon(at: 1, iconUnicode: "\u{e622}")
        first.setItemIcon(at: 2, iconUnicode: "\u{e62d}")
        first.setItemIcon(at: 3, iconUnicode: "\u{e606}")
        first.setItemIcon(at: 4, iconUnicode: "\u{e609}")
        first.setItemIcon(at: 5, iconUnicode: "\u{e607}")
        first.setItemIcon(at: 6, iconUnicode: "\u{e605}")
        first.setItemIcon(at: 7, iconUnicode: "\u{e606}")
        for i in 0..<first.items.count{
            first.setItemTitle(at: i, text: functionCollectionTitles[i])
        }
        first.items[0].addTarget(self, action: #selector(FirstViewController.gotoKebiao), for: .touchUpInside)
        first.items[1].addTarget(self, action: #selector(FirstViewController.gotoTreeHole), for: .touchUpInside)
        first.items[2].addTarget(self, action: #selector(FirstViewController.gotoElectric), for: .touchUpInside)
        first.items[3].addTarget(self, action: #selector(FirstViewController.gotoLRS), for: .touchUpInside)
    }
    
    func gotoKebiao(){
        hidesBottomBarWhenPushed = true
//        navigationController?.setNavigationBarHidden(false, animated: true)
        navigationController?.pushViewController(KBViewController(), animated: true)
        
    }
    
    func gotoTreeHole(){
        hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(THViewController(), animated: true)
    }
    
    func gotoElectric(){
        hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(EBLoginViewController(), animated: true)
    }
    
    func gotoLRS(){
        hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(LRSMenuViewController(), animated: true)
    }
    
    func initActivityCollectionImage(){
        activityCollection = LLCollection(frame: CGRect(x: 0, y: slider.bounds.height + functionSlider.bounds.height + 24, width: view.frame.width, height: 128), row: 2, column: 2)
//        var actImtes: [LLIconButton] = []
        for i in 0..<4{
            var image = UIImage(contentsOfFile: "\(CACHES_PATH)/activity/\(i+1).jpg")
//            let imageView = UIImageView(image: image)
//            sliderImageView.append(imageView)
            if image == nil{
                image = UIImage(contentsOfFile: Bundle.main.path(forResource: "swiperone", ofType: "png")!)
            }
//            activityCollection.setImage(at: i, image: image)
//            activityCollection.setSingleTitle(at: i, title: "话题")
            let btn = LLIconButton(frame: CGRect(x: view.bounds.width/2 * CGFloat(i%2), y: activityCollection.frame.height/2 * CGFloat(i/2), width: view.bounds.width/2, height: activityCollection.frame.height/2))
            btn.backgroundColor = UIColor.white
            btn.iconView.image = image
            btn.titleView.text = "话题\(i+1)"
            btn.titleView.font = UIFont.systemFont(ofSize: 14)
            btn.titleView.numberOfLines = 0
            activityCollection.items[i] = btn
            activityCollection.addSubview(activityCollection.items[i])
            btn.tag = i
            btn.addTarget(self, action: #selector(FirstViewController.gotoTopicDetail(sender:)), for: .touchUpInside)
        }
        
        
        activityCollection.setInnerBorder(borderWeight: 1, color: UIColor.lightGray)
        LLGetActivityImage()
    }
    
    func LLGetActivityImage(){
        //TODO: 获取网络活动图
    }
    
    func LLGetRecommand(){
        //TODO: 获取推荐频道
        
    }
    
    func LLGetPopular(){
        // TODO: 获取热门频道
    }
    
    func showNothingPlaceholder(frame: CGRect) ->UIView{
        let label = UILabel(frame: CGRect(x: 16, y: 0, width: frame.width - 32, height: frame.height))
        label.textAlignment = .center
        label.textColor = UIColor.lightGray
        label.font = UIFont.systemFont(ofSize: 14)
        label.text = emptyPlaceholder
        return label
    }
    
    func getTitleBtnHeader(frame: CGRect, title: String?, btnText: String?) -> (show: UIView, action: UIButton){
        // |16|-->  title  <-- |8| btn |16|
        // |16|title           |8| 64  |16|
        let container = UIView(frame: frame)
        let titleLabel = UILabel(frame: CGRect(x: 16, y: 0, width: frame.width - 32 - 48 - 8, height: frame.height))
        titleLabel.text = title
        container.addSubview(titleLabel)
        
        let moreBtn = UIButton(type: .system)
        moreBtn.frame = CGRect(x: 16 + titleLabel.frame.width + 8, y: 0, width: 48, height: frame.height)
        moreBtn.setTitle(btnText, for: .normal)
        container.addSubview(moreBtn)
        return (container, moreBtn)
    }
    
    func gotoMoreRecommand(){
        print("gotoMoreRecommand")
    }
    
    func gotoMorePopular(){
        print("gotoMorePopular")
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        switch indexPath.section {
        case 1:
            break
        case 2:
            break
        default:
            break
        }
    }
    
    func gotoLocation(){
        hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(CityViewController(), animated: true)
    }
    
    func gotoSearch(){
        hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(SearchViewController(), animated: true)
    }
    
    func gotoTopicDetail(sender: UIButton){
        let topicVC = TopicDetailViewController()
        hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(topicVC, animated: true)
    }
    
    func gotoTopic(sender: UIButton){
        let topicVC = TopicViewController(tab: sender.tag, tabItems: ["热门动态", "热门话题", "推荐话题"] as NSArray)
        hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(topicVC, animated: true)
    }
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
